import { modifyExpiredPwd } from '@/services/system/auth/AuthService';
import { history } from '@@/core/history';
import { useLocation } from '@umijs/max';
import { Alert, Button, Form, Input } from 'antd';
import { DEFAULT_LOGIN_PATH as LOGIN_PATH } from 'kf-web-library';
import queryString from 'query-string';
import React, { useState } from 'react';
import './index.less';

interface AnonModifyPasswordProps {}

const AnonModifyPassword: React.FC<AnonModifyPasswordProps> = (props) => {
  const location = useLocation();
  const locationState = location.state as any;
  const params = queryString.parse(location.search);
  const [form] = Form.useForm();

  const [loading, setLoading] = useState(false);

  let alertMsg = '您已超过3个月未修改密码，为保障您的账号安全，请更改密码';
  if (params?.cause == '400059') {
    alertMsg = '您是（新用户或重置密码后）初次登入系统，为保障您的账号安全，请更改密码以替换掉原始密码';
  }

  return (
    <div className={'anon-modify-password-page-container'}>
      <Alert message={alertMsg} type="warning" style={{ marginBottom: 20 }} />
      <Form
        labelCol={{ span: 24 }}
        wrapperCol={{ span: 24 }}
        form={form}
        initialValues={{
          loginName: locationState.loginName,
          oldPasswd: locationState.password,
        }}
        layout={'vertical'}
        name="login-form"
        autoComplete="off"
        onFinish={async (values) => {
          setLoading(true);
          modifyExpiredPwd(values)
            .then((resp) => {
              if (resp.flag) {
                history.push(LOGIN_PATH);
              }
            })
            .finally(() => {
              setLoading(false);
            });
        }}
      >
        <Form.Item label="用户名" name="loginName" rules={[{ required: true }]}>
          <Input readOnly />
        </Form.Item>

        <Form.Item label="原密码" name={'oldPasswd'} rules={[{ required: true }]}>
          <Input.Password />
        </Form.Item>

        <Form.Item
          name={'newPasswd'}
          label="新密码"
          rules={[
            {
              required: true,
              pattern: /^.*(?=.+)(?=.*\d)(?=.*[a-zA-Z])(?=.*[~!@#$%^&*()_.]).{6,32}$/,
              message: '密码必须包含字母、数字、特殊字符且至少6位',
            },
          ]}
        >
          <Input.Password />
        </Form.Item>

        <Form.Item
          name="confirmPassword"
          label="确认新密码"
          dependencies={['newPasswd']}
          hasFeedback
          rules={[
            {
              required: true,
            },
            ({ getFieldValue }) => ({
              validator(rule, value) {
                if (!value || getFieldValue('newPasswd') === value) {
                  return Promise.resolve();
                }
                return Promise.reject('与新密码不一致!');
              },
            }),
          ]}
        >
          <Input.Password />
        </Form.Item>

        <Form.Item>
          <Button className={'login-submit-btn'} type="primary" htmlType="submit" loading={loading}>
            确定
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

export default AnonModifyPassword;
